var mainWindow = null;

function startup() {

  mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
    .getInterface(Components.interfaces.nsIWebNavigation)
    .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
    .rootTreeItem
    .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
    .getInterface(Components.interfaces.nsIDOMWindow);


  mainWindow.gBrowser.addEventListener("DOMContentLoaded", onPageLoad, false);
  mainWindow.gBrowser.tabContainer.addEventListener("TabSelect", onTabSelect, false);
  updateSidebar(mainWindow.content.document);

}

function onTabSelect(event) {

  var browser = mainWindow.gBrowser.selectedBrowser;
  updateSidebar(browser.contentDocument);

}

function onPageLoad(event) {

  var doc = event.originalTarget;
  var browser = mainWindow.gBrowser.selectedBrowser;

  // For every page loaded, add listener for the unload event to enable
  // receiving notification when the forward or back button is selected.
  doc.defaultView.addEventListener("unload", function (evt) { onPageUnload(evt); }, true);

  // Ensure that the document that was just loaded is the one displayed
  // in the currently selected tab.
  if (doc === browser.contentDocument) updateSidebar(doc);

}

function onPageUnload(event) {

  var doc = event.originalTarget;
  var browser = mainWindow.gBrowser.selectedBrowser;

  // Ensure that the document just unloaded was from the current tab.
  if (doc === browser.contentDocument) updateSidebar(doc);

}

function updateSidebar(doc) {

  var title = doc.title;
  var url = window.content.location.href;

  var title_textbox = document.getElementById("ID_TITLE_TEXTBOX");
  title_textbox.value = title;

  var url_textbox = document.getElementById("ID_URL_TEXTBOX");
  url_textbox.value = url;

}

function shutdown() {
  // Sidebar is unloading
}

window.addEventListener("load", startup, false);
window.addEventListener("unload", shutdown, false);
